<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Module\Base;
use App\Module\Users;
use Request;
use DB;
use Cache;
/**
 * @apiDefine system
 *
 * 系统
 */
class SystemController extends Controller
{
    public function __invoke($method, $action = '')
    {
        $app = $method ? $method : 'main';
        if ($action) {
            $app .= "__" . $action;
        }
        return (method_exists($this, $app)) ? $this->$app() : Base::ajaxError("404 not found (" . str_replace("__", "/", $app) . ").");
    }

    /**
     * 获取设置、保存设置
     *
     * @apiParam {String} type
     * - get: 获取（默认）
     * - save: 保存设置（参数：logo、github、reg、callav、autoArchived、archivedDay）
     */
    public function setting()
    {
        $type = trim(Request::input('type'));
        if ($type == 'save') {
            if (env("SYSTEM_SETTING") == 'disabled') {
                return Base::retError('当前环境禁止修改！');
            }
            $user = Users::authE();
            if (Base::isError($user)) {
                return $user;
            } else {
                $user = $user['data'];
            }
            if (Base::isError(Users::identity('admin'))) {
                return Base::retError('权限不足！', [], -1);
            }
            $all = Request::input();
            foreach ($all AS $key => $value) {
                if (!in_array($key, ['logo', 'github', 'reg', 'callav', 'autoArchived', 'archivedDay'])) {
                    unset($all[$key]);
                }
            }
            $all['logo'] = is_array($all['logo']) ? $all['logo'][0]['path'] : $all['logo'];
            $all['archivedDay'] = intval($all['archivedDay']);
            if ($all['autoArchived'] == 'open') {
                if ($all['archivedDay'] <= 0) {
                    return Base::retError(['自动归档时间不可小于%天！', 1]);
                } elseif ($all['archivedDay'] > 100) {
                    return Base::retError(['自动归档时间不可大于%天！', 100]);
                }
            }
            $setting = Base::setting('system', Base::newTrim($all));
        } else {
            $setting = Base::setting('system');
        }
        $setting['footerText'] = env('WEBSITE_FOOTER', '');
        $setting['logo'] = Base::fillUrl($setting['logo']);
        $setting['enterprise'] = env('ENTERPRISE_SHOW') ? 'show': '';
        return Base::retSuccess('success', $setting ? $setting : json_decode('{}'));
    }

    /**
     * 获取终端详细信息
     */
    public function get__info()
    {
        if (Request::input("key") !== env('APP_KEY')) {
            return [];
        }
        return Base::retSuccess('success', [
            'ip' => Base::getIp(),
            'ip-info' => Base::getIpInfo(Base::getIp()),
            'ip-iscn' => Base::isCnIp(Base::getIp()),
            'header' => Request::header(),
            'token' => Base::getToken(),
            'url' => url('') . Base::getUrl(),
        ]);
    }

    /**
     * 获取IP地址
     */
    public function get__ip() {
        return Base::getIp();
    }

    /**
     * 是否中国IP地址
     */
    public function get__cnip() {
        return Base::isCnIp(Request::input('ip'));
    }

    /**
     * 获取IP地址详细信息
     */
    public function get__ipinfo() {
        return Base::getIpInfo(Request::input("ip"));
    }

    /**
     * 获取websocket地址
     */
    public function get__wsurl() {
        $wsurl = env('LARAVELS_PROXY_URL');
        if (!$wsurl) {
            $wsurl = url('');
            $wsurl = str_replace('https://', 'wss://', $wsurl);
            $wsurl = str_replace('http://', 'ws://', $wsurl);
            $wsurl.= '/ws';
        }
        return Base::retSuccess('success', [
            'wsurl' => $wsurl,
        ]);
    }

    /**
     * UEditor上传图片
     */
    public function ueupload()
    {
        if (Users::token2userid() === 0) {
            return Base::retError('身份失效，等重新登录！');
        }
        $action = trim(Request::input('action'));
        $upload = self::ueditorUploadConfig();
        $data = '';
        switch ($action) {
            case 'config':
                return $upload;
            case $upload['imageActionName']:
                $scale = [intval(Request::input('width')), intval(Request::input('height'))];
                if (!$scale[0] && !$scale[1]) {
                    $scale = [2160, 4160, -1];
                }
                $file = Request::file($upload['imageFieldName']);
                $path = "uploads/picture/" . Users::token2userid() . "/" . date("Ym") . "/";
                $data = Base::upload([
                    "file" => $file,
                    "type" => 'image',
                    "path" =>  $path,
                    "scale" => $scale
                ]);
                break;
            case $upload['videoActionName']:
                $file = Request::file($upload['videoFieldName']);
                $path = "uploads/video/" . Users::token2userid() . "/" . date("Ym") . "/";
                $data = Base::upload([
                    "file" => $file,
                    "type" => 'video',
                    "path" =>  $path
                ]);
                break;
            case $upload['fileActionName']:
                $file = Request::file($upload['fileFieldName']);
                $path = "uploads/files/" . Users::token2userid() . "/" . date("Ym") . "/";
                $data = Base::upload([
                    "file" => $file,
                    "type" => 'file',
                    "path" =>  $path
                ]);

                break;
            case $upload['scrawlActionName']:
                $scale = [intval(Request::input('width')), intval(Request::input('height'))];
                if (!$scale[0] && !$scale[1]) {
                    $scale = [2160, 4160, -1];
                }
                $image64 = trim(Base::getPostValue($upload['scrawlFieldName']));
               
                $path = "uploads/picture/" . Users::token2userid() . "/" . date("Ym") . "/";
                $data = Base::image64save([
                    "image64" => 'data:image/png;base64,'.$image64,
                    "path" => $path,
                    "scale" => $scale
                ]);

                break;
            default:
                return Base::retError('上传失败');
        }
        if (Base::isError($data)) {
            return Base::retError($data['msg']);
        }
        return [
            'state' => 'SUCCESS',
            'url' => $data['data']['url'],
            'title' => $data['data']['name'],
            'original' => $data['data']['name'],
            'type' => $data['data']['ext'],
            'size' => $data['data']['size'],
        ];
    }
    /**
     * 上传图片
     */
    public function imgupload()
    {
        if (Users::token2userid() === 0) {
            return Base::retError('身份失效，等重新登录！');
        }
        $scale = [intval(Request::input('width')), intval(Request::input('height'))];
        if (!$scale[0] && !$scale[1]) {
            $scale = [2160, 4160, -1];
        }
        $path = "uploads/picture/" . Users::token2userid() . "/" . date("Ym") . "/";
        $image64 = trim(Base::getPostValue('image64'));
        $fileName = trim(Base::getPostValue('filename'));
        if ($image64) {
            $data = Base::image64save([
                "image64" => $image64,
                "path" => $path,
                "fileName" => $fileName,
                "scale" => $scale
            ]);
        } else {
            $data = Base::upload([
                "file" => Request::file('image'),
                "type" => 'image',
                "path" => $path,
                "fileName" => $fileName,
                "scale" => $scale
            ]);
        }
        if (Base::isError($data)) {
            return Base::retError($data['msg']);
        } else {
            return Base::retSuccess('success', $data['data']);
        }
    }

    /**
     * 浏览图片空间
     */
    public function imgview()
    {
        if (Users::token2userid() === 0) {
            return Base::retError('身份失效，等重新登录！');
        }
        $publicPath = "uploads/picture/" . Users::token2userid() . "/";
        $dirPath = public_path($publicPath);
        $dirs = $files = [];
        //
        $path = Request::input('path');
        if ($path && is_string($path)) {
            $path = str_replace(array('||', '|'), '/', $path);
            $path = trim($path, '/');
            $path = str_replace('..', '', $path);
            $path = Base::leftDelete($path, $publicPath);
            if ($path) {
                $path = $path . '/';
                $dirPath .= $path;
                //
                $dirs[] = [
                    'type' => 'dir',
                    'title' => '...',
                    'path' => substr(substr($path, 0, -1), 0, strripos(substr($path, 0, -1), '/')),
                    'url' => '',
                    'thumb' => Base::fillUrl('/images/other/dir.png'),
                    'inode' => 0,
                ];
            }
        } else {
            $path = '';
        }
        $list = glob($dirPath . '*', GLOB_BRACE);
        foreach ($list as $v) {
            $filename = basename($v);
            $pathTemp = $publicPath . $path . $filename;
            if (is_dir($v)) {
                $dirs[] = [
                    'type' => 'dir',
                    'title' => $filename,
                    'path' => $pathTemp,
                    'url' => Base::fillUrl($pathTemp),
                    'thumb' => Base::fillUrl('/images/other/dir.png'),
                    'inode' => fileatime($v),
                ];
            } elseif (substr($filename, -10) != "_thumb.jpg") {
                $array = [
                    'type' => 'file',
                    'title' => $filename,
                    'path' => $pathTemp,
                    'url' => Base::fillUrl($pathTemp),
                    'thumb' => $pathTemp,
                    'inode' => fileatime($v),
                ];
                //
                $extension = pathinfo($dirPath . $filename, PATHINFO_EXTENSION);
                if (in_array($extension, array('gif', 'jpg', 'jpeg', 'png', 'bmp'))) {
                    if (file_exists($dirPath . $filename . '_thumb.jpg')) {
                        $array['thumb'] .= '_thumb.jpg';
                    }
                    $array['thumb'] = Base::fillUrl($array['thumb']);
                    $files[] = $array;
                }
            }
        }
        if ($dirs) {
            $inOrder = [];
            foreach ($dirs as $key => $item) {
                $inOrder[$key] = $item['title'];
            }
            array_multisort($inOrder, SORT_DESC, $dirs);
        }
        if ($files) {
            $inOrder = [];
            foreach ($files as $key => $item) {
                $inOrder[$key] = $item['inode'];
            }
            array_multisort($inOrder, SORT_DESC, $files);
        }
        //
        return Base::retSuccess('success', ['dirs' => $dirs, 'files' => $files]);
    }

    /**
     * 上传文件
     */
    public function fileupload()
    {
        if (Users::token2userid() === 0) {
            return Base::retError('身份失效，等重新登录！');
        }
        $path = "/uploads/files/" . Users::token2userid() . "/" . date("Ym") . "/";
        $image64 = trim(Base::getPostValue('image64'));
        $fileName = trim(Base::getPostValue('filename'));
        if ($image64) {
            $data = Base::image64save([
                "image64" => $image64,
                "path" => $path,
                "fileName" => $fileName,
            ]);
        } else {
            $data = Base::upload([
                "file" => Request::file('files'),
                "type" => 'file',
                "path" => $path,
                "fileName" => $fileName,
            ]);
        }
        //
        return $data;
    }

    /**
     * 清理opcache数据
     * @return int
     */
    public function opcache()
    {
        opcache_reset();
        return Base::time();
    }

    static private function ueditorUploadConfig()
    {
        return [
            /* 前后端通信相关的配置,注释只允许使用多行方式 */
            /* 上传图片配置项 */
            'imageActionName' => 'upload-image', /* 执行上传图片的action名称 */
            'imageFieldName' => 'upfile', /* 提交的图片表单名称 */
            'imageMaxSize' => 2 * 1024 * 1024, /* 上传大小限制，单位B */
            'imageAllowFiles' => ['.png', '.jpg', '.jpeg', '.gif', '.bmp'], /* 上传图片格式显示 */
            'imageCompressEnable' => true, /* 是否压缩图片,默认是true */
            'imageCompressBorder' => 1600, /* 图片压缩最长边限制 */
            'imageInsertAlign' => 'none', /* 插入的图片浮动方式 */
            'imageUrlPrefix' => '', /* 图片访问路径前缀 */
            'imagePathFormat' => '/uploads/image/{yyyy}/{mm}/{dd}/', /* 上传保存路径,可以自定义保存路径和文件名格式 */
            /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
            /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
            /* {time} 会替换成时间戳 */
            /* {yyyy} 会替换成四位年份 */
            /* {yy} 会替换成两位年份 */
            /* {mm} 会替换成两位月份 */
            /* {dd} 会替换成两位日期 */
            /* {hh} 会替换成两位小时 */
            /* {ii} 会替换成两位分钟 */
            /* {ss} 会替换成两位秒 */
            /* 非法字符 \  => * ? " < > | */
            /* 具请体看线上文档 => fex.baidu.com/assets/#use-format_upload_filename */

            /* 涂鸦图片上传配置项 */
            'scrawlActionName' => 'upload-scrawl', /* 执行上传涂鸦的action名称 */
            'scrawlFieldName' => 'upfile', /* 提交的图片表单名称 */
            'scrawlPathFormat' => '/uploads/image/{yyyy}/{mm}/{dd}/', /* 上传保存路径,可以自定义保存路径和文件名格式 */
            'scrawlMaxSize' => 2048000, /* 上传大小限制，单位B */
            'scrawlUrlPrefix' => '', /* 图片访问路径前缀 */
            'scrawlInsertAlign' => 'none',

            /* 截图工具上传 */
            'snapscreenActionName' => 'upload-image', /* 执行上传截图的action名称 */
            'snapscreenPathFormat' => '/uploads/image/{yyyy}/{mm}/{dd}/', /* 上传保存路径,可以自定义保存路径和文件名格式 */
            'snapscreenUrlPrefix' => '', /* 图片访问路径前缀 */
            'snapscreenInsertAlign' => 'none', /* 插入的图片浮动方式 */

            /* 抓取远程图片配置 */
            'catcherLocalDomain' => ['127.0.0.1', 'localhost', 'img.baidu.com'],
            'catcherActionName' => 'catch-image', /* 执行抓取远程图片的action名称 */
            'catcherFieldName' => 'source', /* 提交的图片列表表单名称 */
            'catcherPathFormat' => '/uploads/image/{yyyy}/{mm}/{dd}/', /* 上传保存路径,可以自定义保存路径和文件名格式 */
            'catcherUrlPrefix' => '', /* 图片访问路径前缀 */
            'catcherMaxSize' => 2048000, /* 上传大小限制，单位B */
            'catcherAllowFiles' => ['.png', '.jpg', '.jpeg', '.gif', '.bmp'], /* 抓取图片格式显示 */

            /* 上传视频配置 */
            'videoActionName' => 'upload-video', /* 执行上传视频的action名称 */
            'videoFieldName' => 'upfile', /* 提交的视频表单名称 */
            'videoPathFormat' => '/uploads/video/{yyyy}/{mm}/{dd}/', /* 上传保存路径,可以自定义保存路径和文件名格式 */
            'videoUrlPrefix' => '', /* 视频访问路径前缀 */
            'videoMaxSize' => 102400000, /* 上传大小限制，单位B，默认100MB */
            'videoAllowFiles' => [
                '.flv', '.swf', '.mkv', '.avi', '.rm', '.rmvb', '.mpeg', '.mpg',
                '.ogg', '.ogv', '.mov', '.wmv', '.mp4', '.webm', '.mp3', '.wav', '.mid',
            ], /* 上传视频格式显示 */

            /* 上传文件配置 */
            'fileActionName' => 'upload-file', /* controller里,执行上传视频的action名称 */
            'fileFieldName' => 'upfile', /* 提交的文件表单名称 */
            'filePathFormat' => '/uploads/file/{yyyy}/{mm}/{dd}/', /* 上传保存路径,可以自定义保存路径和文件名格式 */
            'fileUrlPrefix' => '', /* 文件访问路径前缀 */
            'fileMaxSize' => 209715500, /* 上传大小限制，单位B，默认200MB */
            'fileAllowFiles' => [
                '.png', '.jpg', '.jpeg', '.gif', '.bmp',
                '.flv', '.swf', '.mkv', '.avi', '.rm', '.rmvb', '.mpeg', '.mpg',
                '.ogg', '.ogv', '.mov', '.wmv', '.mp4', '.webm', '.mp3', '.wav', '.mid',
                '.rar', '.zip', '.tar', '.gz', '.7z', '.bz2', '.cab', '.iso',
                '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt', '.md', '.xml',
            ], /* 上传文件格式显示 */

            // /* 列出指定目录下的图片 */
            // 'imageManagerActionName' => 'list-image', /* 执行图片管理的action名称 */
            // 'imageManagerListPath' => '/uploads/image/', /* 指定要列出图片的目录 */
            // 'imageManagerListSize' => 20, /* 每次列出文件数量 */
            // 'imageManagerUrlPrefix' => '', /* 图片访问路径前缀 */
            // 'imageManagerInsertAlign' => 'none', /* 插入的图片浮动方式 */
            // 'imageManagerAllowFiles' => ['.png', '.jpg', '.jpeg', '.gif', '.bmp'], /* 列出的文件类型 */

            // /* 列出指定目录下的文件 */
            // 'fileManagerActionName' => 'list-file', /* 执行文件管理的action名称 */
            // 'fileManagerListPath' => '/uploads/file/', /* 指定要列出文件的目录 */
            // 'fileManagerUrlPrefix' => '', /* 文件访问路径前缀 */
            // 'fileManagerListSize' => 20, /* 每次列出文件数量 */
            // 'fileManagerAllowFiles' => [
            //     '.png', '.jpg', '.jpeg', '.gif', '.bmp',
            //     '.flv', '.swf', '.mkv', '.avi', '.rm', '.rmvb', '.mpeg', '.mpg',
            //     '.ogg', '.ogv', '.mov', '.wmv', '.mp4', '.webm', '.mp3', '.wav', '.mid',
            //     '.rar', '.zip', '.tar', '.gz', '.7z', '.bz2', '.cab', '.iso',
            //     '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt', '.md', '.xml',
            // ], /* 列出的文件类型 */
        ];
    }
     /**
     * 获取全局未完成任务清单
     * @apiParma {String} type:done,doing
     */
    public function untasks()
    {
        $user = Users::authE();
        $type=Request::input('type');
        if (Base::isError($user)) {
            return $user;
        } else {
            $user = $user['data'];
        }
        if (strpos($user['profession'],'主管')<=0) {
            return Base::retError('权限不足！');
        }
        if($type==='done'){
            $tasks=Cache::remember('donetaskscache',600,function(){
                $res=DB::select("select username,coalesce(nullif(nickname,''),username) nickname,profession,json_object_agg(id,array[pname,lblname,title,(COALESCE(nullif(startdate,0),indate))::text,completedate::text,level::text])::json tasks from (select t.*,u.nickname,u.profession,coalesce(l.title,'self') lblname,COALESCE(p.title,'self') pname from (select * from ".env('DB_PREFIX')."project_task where username in (select username from ".env('DB_PREFIX')."users where disabled=0) and complete='t' and \"delete\"='f' and archived=0 order by projectid,labelid )  t left join ".env('DB_PREFIX')."project_label l on t.labelid=l.id left join ".env('DB_PREFIX')."project_lists p on t.projectid=p.id left join ".env('DB_PREFIX')."users u on t.username=u.username ) t where complete='t' and \"delete\"='f'   group by username,nickname,profession order by profession,coalesce(nullif(nickname,''),username)");
                foreach($res as &$resitm){
                    $resitm->tasks=json_decode($resitm->tasks);
                }
                return $res;
            });
        }else{
            $tasks=Cache::remember('untaskscache',600,function(){
                $res=DB::select("select username,coalesce(nullif(nickname,''),username) nickname,profession,json_object_agg(id,array[pname,lblname,title,(COALESCE(nullif(startdate,0),indate))::text::text,enddate::text,level::text]) tasks from (select t.*,u.nickname,u.profession,coalesce(l.title,'self') lblname,COALESCE(p.title,'self') pname from (select * from ".env('DB_PREFIX')."project_task where username in (select username from ".env('DB_PREFIX')."users where disabled=0) and complete='f' and \"delete\"='f' and archived=0 order by projectid,labelid )  t left join ".env('DB_PREFIX')."project_label l on t.labelid=l.id left join ".env('DB_PREFIX')."project_lists p on t.projectid=p.id left join ".env('DB_PREFIX')."users u on t.username=u.username ) t where complete='f' and \"delete\"='f'   group by username,nickname,profession order by profession,coalesce(nullif(nickname,''),username)");
                foreach($res as &$resitm){
                    $resitm->tasks=json_decode($resitm->tasks);
                }
                return $res;
            });
        }
        
        return Base::retSuccess('success', $tasks);
    }
}
